import React, { memo, useEffect, useState } from 'react';
import { Table, Button, Form, message, Popconfirm } from 'antd';
import authHelper from '@/utils/auth/helper';
import { GradeSelector } from '@/pages/Organization/Job/components';
import { Icon, Operates } from '@/pages/Recruitment/components';
import FormItem from '@/pages/Organization/Job/components/PostForm/PostFormItem';
import { useGradeList, usePositionTypeList } from '@/pages/Organization/Job/hooks';
import {
    getSeniorConditionList,
    onAddSeniorCondition,
    onUpdateSeniorCondition,
    onDeleteCondition
} from '@/pages/Recruitment/TalentsManagement/service';
import AuthComponent from '@/utils/auth/AuthComponent';
import styles from './index.less';

const { checkCode } = authHelper;

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => {
    const [editing, setEditing] = useState(false);
    return (
        <EditableContext.Provider value={{ form, editing, setEditing }}>
            <tr {...props} />
        </EditableContext.Provider>
    );
};

const EditableFormRow = Form.create()(EditableRow);

const EditableTable = memo(() => {
    const [staticData] = useState({
        isEditing: false
    });
    const [loading, setLoading] = useState(false);
    const [, positionTypeList] = usePositionTypeList();
    const [, gradeList] = useGradeList();
    // console.log(positionTypeList, gradeList, '=====');
    const [dataSource, setDataSource] = useState([]);
    const getPositionName = code => {
        let str = '';
        if (code) {
            const preCode = code.slice(0, 3);
            const nextCode = code.length === 3 ? '' : code;
            // eslint-disable-next-line no-restricted-syntax
            for (const position of positionTypeList) {
                if (position.positionTypeCode === preCode) {
                    str += position.positionTypeName;
                }
                if (!nextCode) break;
                // eslint-disable-next-line no-restricted-syntax
                for (const child of position.children) {
                    if (child.positionTypeCode === nextCode) {
                        str += ` | ${child.positionTypeName}`;
                        break;
                    }
                }
            }
            // eslint-disable-next-line consistent-return
            return str;
        }
        // eslint-disable-next-line consistent-return
        return str;
    };
    const getPositionInitialInfo = (text = '') => {
        const value = {};
        const preCode = text.slice(0, 3);
        const nextCode = text.length === 3 ? '' : text;
        if (preCode) {
            value.firstPositionCode = preCode;
        }
        if (nextCode) {
            value.secondPositionCode = nextCode;
        }
        return value;
    };
    const getRankName = code => {
        let str = '';
        if (code) {
            const codeArr = code.split(',');
            codeArr.forEach((item, index) => {
                // eslint-disable-next-line no-restricted-syntax
                for (const rank of gradeList) {
                    if (item === rank.rankCode) {
                        str += index === codeArr.length - 1 ? rank.rankValue : `${rank.rankValue}、`;
                        break;
                    }
                }
            });
        }
        return str;
    };
    const getConditionList = async () => {
        try {
            setLoading(true);
            const { data, code, msg } = await getSeniorConditionList();
            if (code === 10000) {
                setDataSource(data);
            } else {
                message.error(msg);
            }
            setLoading(false);
        } catch (e) {
            console.log('获取高级库入库条件出错！');
            setLoading(false);
        }
    };
    const handleAdd = () => {
        if (staticData.isEditing) {
            message.error('请先完成编辑！');
            return;
        }
        const newData = {
            key: Math.random(),
            isNew: true,
            positionTypeCode: '',
            rankCodes: ''
        };
        setDataSource([...dataSource, newData]);
    };
    const handleSave = async (values, record, value) => {
        const { setEditing } = value;
        try {
            const { id } = record;
            const params = {
                positionTypeCode: values.secondPositionCode || values.firstPositionCode,
                rankCodes: values.rankCodes && values.rankCodes.length && values.rankCodes.join(',')
            };
            if (id) {
                params.id = id;
            }
            setLoading(true);
            const { code, msg } = id ? await onUpdateSeniorCondition(params) : await onAddSeniorCondition(params);
            if (code === 10000) {
                setEditing(false);
                staticData.isEditing = false;
                message.success(id ? '更新成功!' : '添加成功！');
                await getConditionList();
            } else {
                message.error(msg);
            }
            setLoading(false);
        } catch (e) {
            setLoading(false);
            console.log(e);
        }
    };
    const handleDelete = async record => {
        try {
            setLoading(true);
            const { code, msg } = await onDeleteCondition(record.id);
            if (code === 10000) {
                message.success('删除成功！');
                await getConditionList();
            } else {
                message.error(msg);
            }
            setLoading(false);
        } catch (e) {
            console.log(e);
            setLoading(false);
        }
    };

    const columns = [
        {
            title: '职位类别',
            dataIndex: 'positionTypeCode',
            width: 400,
            render: (text, record) => (
                <EditableContext.Consumer>
                    {value => {
                        const { form } = value;
                        return (
                            <>
                                {value.editing ? (
                                    <FormItem
                                        required
                                        form={form}
                                        initialFormInfo={getPositionInitialInfo(text)}
                                        label=""
                                        positionTypeList={positionTypeList}
                                        prop={['firstPositionCode', 'secondPositionCode']}
                                    />
                                ) : (
                                    getPositionName(record.positionTypeCode)
                                )}
                            </>
                        );
                    }}
                </EditableContext.Consumer>
            )
        },
        {
            title: '职级',
            dataIndex: 'rankCodes',
            render: (text, record) => (
                <EditableContext.Consumer>
                    {value => {
                        const { form } = value;
                        const { getFieldDecorator } = form;
                        return value.editing ? (
                            <Form.Item>
                                {getFieldDecorator('rankCodes', {
                                    initialValue: text ? text.split(',') : [],
                                    // validateTrigger: 'onSubmit', // 设置进行表单验证的时机为onSubmit
                                    rules: [
                                        {
                                            validator(_, val, callback) {
                                                if (val && val.length) {
                                                    callback();
                                                    return;
                                                }
                                                callback('职级不能为空！');
                                            }
                                        }
                                    ]
                                })(<GradeSelector mode="multiple" maxTagCount={5} />)}
                            </Form.Item>
                        ) : (
                            getRankName(record.rankCodes)
                        )
                    }}
                </EditableContext.Consumer>
            )
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 100,
            render: (text, record) => (
                <EditableContext.Consumer>
                    {value => {
                        const { form, editing, setEditing } = value;
                        if (record.isNew) {
                            setEditing(true);
                            staticData.isEditing = true;
                        }
                        const operates = editing
                            ? [
                                <Icon
                                    type="confirm_o"
                                    title="保存"
                                    onClick={() => {
                                        form.validateFields((errors, values) => {
                                            console.log(errors, values);
                                            if (!errors) {
                                                handleSave(values, record, value);
                                            }
                                        });
                                    }}
                                />,
                                <Icon
                                    type="cancel_o"
                                    title="取消"
                                    onClick={() => {
                                        staticData.isEditing = false; // 0_0
                                        // eslint-disable-next-line no-unused-expressions
                                        record.isNew
                                            ? setDataSource(dataSource.filter(item => item.key !== record.key))
                                            : setEditing(false);
                                    }}
                                />
                            ]
                            : [
                                <AuthComponent code="office:recruitment:setting:talent:edit">
                                    <Icon
                                        type="listfunction_edit_icon_default"
                                        title="编辑"
                                        onClick={() => {
                                            if (staticData.isEditing) {
                                                message.error('请先完成编辑！');
                                                return;
                                            }
                                            staticData.isEditing = true;
                                            setEditing(true);
                                        }}
                                    /></AuthComponent>,
                                <AuthComponent code="office:recruitment:setting:talent:delete">
                                    <Popconfirm
                                        title="确认是否删除?"
                                        onConfirm={() => {
                                            if (staticData.isEditing) {
                                                message.error('请先完成编辑！');
                                                return;
                                            }
                                            handleDelete(record);
                                        }}
                                    >
                                        <Icon type="DeleteIcon" title="删除" />
                                    </Popconfirm>
                                </AuthComponent>
                            ];
                        return <Operates operates={operates} />;
                    }}
                </EditableContext.Consumer>
            )
        }
    ];
    const components = {
        body: {
            row: EditableFormRow
        }
    };
    useEffect(() => {
        getConditionList();
    }, []);
    return (
        <div>
            <Table
                loading={loading}
                components={components}
                rowClassName={() => styles.editableRow}
                bordered
                dataSource={dataSource}
                columns={columns}
                pagination={false}
            />
            {checkCode('office:recruitment:setting:talent:add') && (
                <>
                    <Button type="dashed" icon="plus" block style={{ margin: '10px 0' }} onClick={handleAdd}>
                        添加入库条件
                    </Button>
                </>
            )}
        </div>
    );
});
export default EditableTable;
